package com.pyi.config.mybatisplus.controller;

import com.pyi.config.mybatisplus.model.Book;
import com.pyi.config.mybatisplus.service.impl.BookServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * @author pyi
 * @date 2019-04-10
 * @CacheConfig(cacheNames = "book") 抽取缓存的公共配置，若启用，下面的value都不需要指定了
 *
 */
//@CacheConfig(cacheNames = "book")
@RestController
@RequestMapping("book")
public class BookController {

    @Autowired
    private BookServiceImpl bookServiceImpl;

    /**
     * @Cacheable  方法运行之前先去查询缓存，没有则将查询结果进行缓存
     * @return
     */
    @GetMapping("/detail/{id}")
    @Cacheable(value = "book",key = "#id",unless = "#result == null ")
    public Object getById(@PathVariable("id") Integer id) {

        return bookServiceImpl.getById(id);
    }


    /**
     * @CachePut   是在方法运行好后进行缓存,所以方法一定会执行
     * @param book
     * @return
     */
    @GetMapping("/update")
    @CachePut(value = "book",key = "#book.bookId")
    public Object update(Book book){

        bookServiceImpl.updateById(book);
//        Book book1 = bookServiceImpl.getById(book.getBookId());
        return book;
    }


    /**
     * @CacheEvict  清除缓存
     * allEntries默认false，true时删除所有value为book的缓存
     * beforeInvocation 默认false，是在方法执行之后执行的
     */
    @CacheEvict(value = "book",/*key = "#id",*/allEntries = true)
    @GetMapping("/delete")
    public String delete(Integer id){

        return "success";
    }


    /**
     * @Caching 制定复杂缓存规则
     * @param bookName
     * @return
     */
    @Caching(
            cacheable = {
                    @Cacheable(value = "book",key = "#bookName")
            },
            put = {
                    @CachePut(value = "book",key = "#result.bookId"),
                    @CachePut(value = "book",key = "#result.bookAuthor")
            }
    )
    @GetMapping("/name/{bookName}")
    public Object getBook(@PathVariable("bookName") String bookName){
        return bookServiceImpl.getById(1);
    }

}
